<script lang="ts" setup>
import { computed, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useShoppingCartStore } from '@/stores';
import { createOrder } from '../../api/order';

const editable = ref(false);
const shoppingCart = ref<any>({});
const merchants = ref<any>([]);
const shoppingCartStore = useShoppingCartStore();
const selectedIds = ref<any>(new Set());

const buttonStyle = computed(() => {
	return {
		borderRadius: '16rpx',
		fontSize: '30rpx',
		padding: '32rpx 54rpx',
		background: 'linear-gradient( 94deg, #0049D6 0%, #0023AD 100%)'
	};
});

const deleteButtonStyle = computed(() => {
	return {
		borderRadius: '16rpx',
		fontSize: '30rpx',
		padding: '32rpx 54rpx'
	};
});

onLoad(() => {
	fetchData();
});

async function fetchData() {
	shoppingCart.value = await shoppingCartStore.getShoppingCart();
	const groups = [];
	for (let i = 0; i < shoppingCart.value.products.length; i++) {
		const product = shoppingCart.value.products[i];
		const finded = groups.find((item: any) => item.id === product.merchantId);
		if (finded) {
			finded.children.push(product);
		} else {
			groups.push({
				id: product.merchantId,
				name: product.merchantName,
				children: [{ ...product }]
			});
		}
	}
	merchants.value = groups;
}

async function handleCreateOrder() {
	if (shoppingCart.value.totalAmount > 0) {
		await createOrder();
		uni.navigateTo({
			url: '/pages/order-confirm/order-confirm'
		});
	} else {
		uni.showModal({
			content: '暂无商品，请先选购商品再进行结算',
			showCancel: false
		});
	}
}

async function handleQuantityChange(item: any) {
	await shoppingCartStore.updateQuantity({ id: item.id, quantity: item.quantity });
	fetchData();
}

function handleRadioChange(item: any) {
	if (item.checked) {
		selectedIds.value.add(item.value);
	} else {
		selectedIds.value.delete(item.value);
	}
}

async function handleRemove() {
	await shoppingCartStore.deleteProducts({ ids: [...selectedIds.value] });
	fetchData();
}
</script>

<template>
	<x-container direction="vertical" bg-color="#F8F8F8" min-height="100vh" gap="20rpx">
		<x-container justify="between" bg-color="#fff" padding="16rpx 30rpx">
			<x-text :size="28">共{{ shoppingCart.totalItems }}件商品</x-text>
			<x-text color="#333333" :size="28" v-if="merchants.length > 0" @tap="editable = !editable">{{ editable ? '退出管理' : '管理' }}</x-text>
		</x-container>
		<template v-for="merchant in merchants" v-if="merchants.length > 0">
			<x-container direction="vertical" justify="between" bg-color="#fff" padding="32rpx" gap="32rpx">
				<x-text-icon direction="horizontal" type="store" :size="28" :text-props="{ size: 28, bold: true }">{{ merchant.name }}</x-text-icon>
				<x-row v-for="item in merchant.children" align="center">
					<x-col flex="60rpx" v-if="editable">
						<x-radio :value="item.id" @change="handleRadioChange"></x-radio>
					</x-col>
					<x-col flex="180rpx">
						<x-image width="160rpx" height="160rpx" :prefix="false" :src="item.cover?.url"></x-image>
					</x-col>
					<x-col flex="auto">
						<x-container direction="vertical" justify="between" height="160rpx">
							<x-space direction="vertical" align="start" :size="20">
								<x-text color="#222222" :size="28" bold>{{ item.productName }}</x-text>
							</x-space>
							<x-container justify="between" align="end" width="100%">
								<x-space align="end" :size="6" style="margin-bottom: 10rpx">
									<x-text color="#FA5732" :size="26">预估到手</x-text>
									<dlk-currency :value="parseFloat(item.priceUnit || 0)" :size="36"></dlk-currency>
								</x-space>
								<dlk-quantity v-model="item.quantity" @change="handleQuantityChange(item)"></dlk-quantity>
							</x-container>
						</x-container>
					</x-col>
				</x-row>
			</x-container>
		</template>
		<x-container justify="center" padding="100rpx" v-else>
			<x-empty title="暂无商品"></x-empty>
		</x-container>
	</x-container>
	<x-action-bar>
		<x-container justify="between" align="center">
			<view>
				<x-checkbox v-if="editable">全选</x-checkbox>
			</view>
			<x-space align="center" :size="24">
				<x-space direction="vertical" v-if="!editable">
					<x-space align="end" :size="0">
						<x-text :size="26">合计：</x-text>
						<dlk-currency :value="parseFloat(shoppingCart.totalAmount || 0)" :size="36"></dlk-currency>
					</x-space>
					<x-text color="#FA5732" :size="22" align="right">已优惠￥0.00</x-text>
				</x-space>
				<x-button type="primary" :custom-style="buttonStyle" v-if="!editable" @tap="handleCreateOrder">结算（{{ shoppingCart.totalItems }}）</x-button>
				<x-button type="danger" :custom-style="deleteButtonStyle" v-if="editable" @tap="handleRemove">删除</x-button>
			</x-space>
		</x-container>
	</x-action-bar>
</template>
